package miage.rest.resource.candidature;

import com.thoughtworks.xstream.XStream;
import java.sql.SQLException;

import java.util.List;

import miage.rest.db.Database;
import miage.rest.model.Candidat;
import miage.rest.model.Candidature;
import miage.rest.resource.ResourceError;
import miage.rest.routing.UriTemplateFinder;
import miage.rest.validation.LongRangeValidator;
import miage.rest.xml.XstreamRepresentation;
import miage.rest.xml.xstream.converter.HrefConverter;

import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

/**
 *
 * @author Schwartz Michaël
 */
public class CandidatResource extends ServerResource {

    private final Database database;
	private final UriTemplateFinder uriTemplateFinder;

	private Candidat candidat;

    public CandidatResource(Database database, UriTemplateFinder uriTemplateFinder) {
        super();
        this.database = database;
		this.uriTemplateFinder = uriTemplateFinder;
    }

	@Override
	protected void doInit() throws ResourceException {

		final String sqlCandidat = "SELECT * FROM candidat WHERE id_candidat = ?";
		final String sqlCandidatures = "SELECT id_candidature from candidature WHERE id_candidat = ?";


		Long idCandidat = null;
		String idCandidatAttribute = getRequest().getAttributes().get("idCandidat").toString();
		LongRangeValidator longRangeValidator = new LongRangeValidator(1l, null);

		//Validation de l'id du candidat
		if (longRangeValidator.isValid(idCandidatAttribute)) {
			idCandidat = Long.parseLong(idCandidatAttribute);
		} else {
			getResponse().setEntity(ResourceError.getNewRepresentation("invalidCandidatId"));
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
		}

		//Récupération du candidat
		try {
			candidat = database.fetchRow(sqlCandidat, Candidat.class, idCandidat);
		
			if (candidat != null) {
				//Récupération des candidatures du candidat
				List<Candidature> candidatures = database.fetchAll(sqlCandidatures, Candidature.class, candidat.getIdCandidat());
				candidat.setCandidatures(candidatures);

			} else {
				setExisting(false);
			}

		} catch (SQLException ex) {

			throw new ResourceException(Status.SERVER_ERROR_INTERNAL, ex);
		}

	}



    /**
	 * Représentation XML d'un candidat en réponse à une requête GET.
	 *
	 * @require candidat != null
     */
    @Get
    public Representation doGet() {
		assert(candidat != null);

        Representation response = null;

		//Création d'une représentation XStream du candidat
		response = new XstreamRepresentation<Candidat>(candidat);
		XStream xstream = ((XstreamRepresentation)response).getXstream();

		//Ajout de l'intégration des liens href  pour la classe Candidature
		//par l'intermédiaire de la classe HrefConverter
		xstream.registerConverter(new HrefConverter(
				Candidature.class,
				xstream.getConverterLookup(),
				uriTemplateFinder.find(CandidatureResource.class)
		));

        return response;
    }
	
}
